<?php

namespace Trawind\Helpers;


use Illuminate\Support\Facades\Redis;

/**
 * Class ExchangeRateHelper
 * @package Trawind\Helpers
 */
class ExchangeRateHelper
{


    /**
     * @param  string  $useCurrency
     * @param  string  $toCurrency
     * @return mixed|null
     */
    public static function get(string $useCurrency, string $toCurrency)
    {
        $result = static::request($useCurrency);
        return $result[$toCurrency] ?? null;
    }


    /**
     * @param  string  $currency
     * @return array|mixed
     */
    public static function request(string $currency)
    {
        $key = "exchange_rate_map:{$currency}";
        if (is_null($result = Redis::get($key))) {
            $response = HttpClientHelper::guzzle()
                ->get('https://api.exchangerate-api.com/v4/latest/'.$currency);

            $result= serialize(HttpClientHelper::getResponseContent($response)['rates'] ?? []);
            Redis::setex($key, 60 * 120, $result);
        }

        return unserialize($result);
    }


    /**
     * @param $name
     * @param $arguments
     * @return mixed|null
     */
    public static function __callStatic($name, $arguments)
    {
        return static::get($name, $arguments[0] ?? '');
    }
}